package com.hera.base.web.vaadin.mantenimiento;

import static com.hera.base.util.InputData.getObjectData;
import static com.hera.base.util.InputData.getStringData;
import static com.hera.base.util.InputData.getDoubleData;

import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;

import com.hera.base.util.Constantes;
import com.hera.base.util.FiltroDTO;
import com.hera.base.util.TableCustom;
import com.hera.base.web.BaseUI;
import com.hera.base.web.IConfirmDialog;
import com.hera.base.web.MantenimientoMaestroDetalle;
import com.hera.base.web.SimpleAlertDialog;
import com.hera.process.config.domain.Datasource;
import com.hera.process.config.domain.ParameterDetail;
import com.hera.process.config.rest.delegate.ConfigDelegate;
import com.hera.process.config.rest.delegate.WorkflowDelegate;
import com.hera.process.workflow.domain.Process;
import com.hera.web.vaadin.flujo.ProcessDetailUI;
import com.vaadin.annotations.AutoGenerated;
import com.vaadin.data.Property.ValueChangeEvent;
import com.vaadin.data.Property.ValueChangeListener;
import com.vaadin.data.util.BeanItemContainer;
import com.vaadin.event.FieldEvents.TextChangeEvent;
import com.vaadin.event.FieldEvents.TextChangeListener;
import com.vaadin.server.ThemeResource;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.ComboBox;
import com.vaadin.ui.HorizontalLayout;
import com.vaadin.ui.Label;
import com.vaadin.ui.TextArea;
import com.vaadin.ui.TextField;
import com.vaadin.ui.UI;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;

public class ProcessUI extends BaseUI implements MantenimientoMaestroDetalle,ClickListener {

	/*- VaadinEditorProperties={"grid":"RegularGrid,20","showGrid":true,"snapToGrid":true,"snapToObject":true,"movingGuides":false,"snappingDistance":10} */

	@AutoGenerated
	private VerticalLayout mainLayout;
	@AutoGenerated
	private VerticalLayout verticalLayout_1;
	@AutoGenerated
	private HorizontalLayout horizontalLayout_1;
	@AutoGenerated
	private VerticalLayout verticalLayout_5;
	@AutoGenerated
	private HorizontalLayout horizontalLayout_2;
	@AutoGenerated
	private Button btnPublicar;
	@AutoGenerated
	private Button btnDetalle;
	@AutoGenerated
	private HorizontalLayout horizontalLayout_5;
	@AutoGenerated
	private Button btnNuevo;
	@AutoGenerated
	private Button btnEliminar;
	@AutoGenerated
	private Button btnModificar;
	@AutoGenerated
	private TextArea txaDescripcion;
	@AutoGenerated
	private ComboBox cmbProcessCat;
	@AutoGenerated
	private TextField txtTimeAmount;
	@AutoGenerated
	private ComboBox cmbUnitTime;
	@AutoGenerated
	private ComboBox cmbDatasource;
	@AutoGenerated
	private TextField txtNombre;
	@AutoGenerated
	private Label lbltitulo;
	@AutoGenerated
	private HorizontalLayout lytMaestroProcess;
	@AutoGenerated
	private HorizontalLayout lytTablaProcess;
	@AutoGenerated
	private TableCustom tblfMaestro;
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	/**
	 * The constructor should first build the main layout, set the
	 * composition root and then do any custom initialization.
	 *
	 * The constructor will not be automatically regenerated by the
	 * visual editor.
	 */
	public ProcessUI() {
		buildMainLayout();		
		setCompositionRoot(mainLayout);

		// TODO add user code here
	}

	private static final Logger log = Logger.getLogger(ProcessUI.class);
	
	
	
	@Autowired
	WorkflowDelegate workflowDelegate;
	@Autowired
	ConfigDelegate configDelegate;
	boolean esNuevo;
	boolean esNuevoDetalle;

	com.hera.process.workflow.domain.Process mainEntity;
	
	@Override
	public void buttonClick(ClickEvent event) {
		if(event.getButton().equals(btnEliminar)){
			eliminarMaestro();
		}else if(event.getButton().equals(btnModificar)){
			guardarMaestro();
		}else if(event.getButton().equals(btnNuevo)){
			guardarMaestro();
		}else if(event.getButton().equals(btnDetalle)){
			verFlujo();
		}else if(event.getButton().equals(btnPublicar)){
			validar();
		}
		
	}


	@Override
	public void cargarFormulario() {
	
		log.info("INCIO +++++++++");
		esNuevo=true;
		mainEntity=null;
		txtNombre.addStyleName("fieldRequired");
		txaDescripcion.addStyleName("fieldRequired");
		cmbDatasource.setStyleName("fieldRequired2");
		txtTimeAmount.setStyleName("fieldRequired");
		BeanItemContainer<Datasource> datasourcebean = new BeanItemContainer<Datasource>(Datasource.class);
		datasourcebean.addAll(configDelegate.findAllDatasource(new FiltroDTO()));
		cmbDatasource.setContainerDataSource(datasourcebean);
		cmbDatasource.setItemCaptionPropertyId("schema");
		cmbDatasource.setInputPrompt("Datasource");
		
		BeanItemContainer<ParameterDetail> unitTime = new BeanItemContainer<ParameterDetail>(ParameterDetail.class);
		ParameterDetail listsDetail = new ParameterDetail();
		listsDetail.setIdParameterDetail(Constantes.UNIDADTIEMPO.ID);
		unitTime.addAll(configDelegate.findDetailList(listsDetail));
		cmbUnitTime.setStyleName("fieldRequired");
		cmbUnitTime.setContainerDataSource(unitTime);
		cmbUnitTime.setItemCaptionPropertyId("name");
		cmbUnitTime.setInputPrompt("Unidad de Tiempo");
		
		BeanItemContainer<ParameterDetail> catProcess = new BeanItemContainer<ParameterDetail>(ParameterDetail.class);
		ParameterDetail listsDetail1 = new ParameterDetail();
		listsDetail1.setIdParameterDetail(Constantes.CATEGORIAPROCESO.ID);
		catProcess.addAll(configDelegate.findDetailList(listsDetail1));
		cmbProcessCat.setContainerDataSource(catProcess);
		cmbProcessCat.setItemCaptionPropertyId("name");
		cmbProcessCat.setInputPrompt("Categoria");
		
		
		btnModificar.setVisible(false);
		btnModificar.addClickListener(this);
     	btnModificar.setCaption("");     	
     	btnModificar.setIcon(new ThemeResource("images/trash_20_1.png"));
		
		
		btnEliminar.setVisible(false);
		btnEliminar.addClickListener(this);
		btnEliminar.setCaption("");
		btnEliminar.setIcon(new ThemeResource("images/trash_20_2.png"));
		
		btnPublicar.setVisible(false);
		btnPublicar.addClickListener(this);
		btnPublicar.setCaption("Publicar");
		btnPublicar.setIcon(new ThemeResource("images/trash_20_3.png"));
		
		btnNuevo.setVisible(false);
		btnNuevo.addClickListener(this);
		btnNuevo.setCaption("Nuevo");
		
		btnDetalle.setVisible(false);
		btnDetalle.addClickListener(this);
		btnDetalle.setCaption("Flujo");
		
		horizontalLayout_5.setStyleName("buttoncust");
		horizontalLayout_2.setStyleName("buttoncust");
				
		tblfMaestro.setTitulo(" PROCESO ");
		tblfMaestro.setHeight("200px");
		
		tblfMaestro.addColumn("name", "Nombre", 150, true, String.class);
		tblfMaestro.addColumn("description", "Descripcion", 250, true, String.class);
		
		tblfMaestro.construir();
		tblfMaestro.addTextChangeListener(new TextChangeListener() {		
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void textChange(TextChangeEvent event) {
				buscarMaestro(event);				
			}
		});
		
		tblfMaestro.addValueChangeListener(new ValueChangeListener() {
			
			/**
			 * 
			 */
			private static final long serialVersionUID = 1L;

			@Override
			public void valueChange(ValueChangeEvent event) {
				mainEntity=(com.hera.process.workflow.domain.Process)tblfMaestro.getSelectedItem(event);
				esNuevo=(mainEntity==null);
				tblfMaestro.limpiarFiltro();
				if(esNuevo){
					limpiarMaestro();
					
					btnEliminar.setVisible(false);
					btnModificar.setVisible(false);
					btnDetalle.setVisible(false);
					btnPublicar.setVisible(false);
				}else{
					btnEliminar.setVisible(true);
					btnNuevo.setVisible(false);
					btnModificar.setVisible(true);
					btnDetalle.setVisible(true);
					btnPublicar.setVisible(true);
					btnModificar.setCaption("");
					//btnModificar.setCaption("Modificar");
					
					txtNombre.setValue(mainEntity.getName());
					txaDescripcion.setValue(mainEntity.getDescription());
					cmbDatasource.setValue(mainEntity.getDatasource());
					cmbProcessCat.setValue(mainEntity.getProcessCategory());
					cmbUnitTime.setValue(mainEntity.getTimeUnit());
					txtTimeAmount.setValue(mainEntity.getTimeAmount()==null?"0.0":mainEntity.getTimeAmount().toString());
				}
				
				log.info("Fin Cargar Formulario PROCESS ");				
			}
		});		
	}

	@Override
	public void buscarMaestro() {
		buscarMaestro(null);
		
	}

	@Override
	public void buscarMaestro(TextChangeEvent event) {
		log.info("inicio Buscar Process");
		
		FiltroDTO filtroDTO=tblfMaestro.getFiltroDTO(event);
//		ADDPARAMERTRO SETEAMOS LA FILA LLAMANDO AL ATRIBUTO Y SE COLOCA FALSE DE ESTADO 0 PASA A 1 Y OCULTA LA FILA
		filtroDTO.addParametro("flagDelete", false);
		
		List<Process> lstProcess=workflowDelegate.findAllProcesses(filtroDTO);
		tblfMaestro.setLstData(lstProcess);
		limpiarMaestro();
		log.info("fin FindDatasource");
	}

	@Override
	public void limpiarMaestro() {
		log.info("inicio limpiarMaestro");
		btnNuevo.setVisible(true);
		btnNuevo.setCaption("Nuevo");
		txtNombre.setValue("");
		txaDescripcion.setValue("");
		cmbDatasource.setValue(null);
		cmbProcessCat.setValue(null);
		cmbUnitTime.setValue(null);
		txtTimeAmount.setValue("");
		
		log.info("fin limpiarMaestro");
		
	}
	
	public void validar(){
		try{
			if(workflowDelegate.validarProceso(mainEntity)){
				mostrarConfirmacion(new IConfirmDialog() {			
					@Override
					public void cancelar(Button event, Window window) {
						window.close();
					}			
					@Override
					public void aceptar(Button event, Window window) {
						publicar();
						window.close();
					}
				}, "proceso.mensaje.confirmacion.publicar");
			}else{
				mostrarAlerta(new SimpleAlertDialog(), "proceso.mensaje.alerta.publicar", "Hay errores en el proceso, proceda a revisar");
			}
		}catch(Exception e){
			mostrarAlerta(new SimpleAlertDialog(), "proceso.mensaje.alerta.publicar", e.getMessage());
		}
		
	}

	public void publicar() {

		log.info("inicio publicar");
		workflowDelegate.publicarProceso(mainEntity);
			
		
	}
	@Override
	public void eliminarMaestro() {
		
		log.info("inicio eliminarMaestro");
		workflowDelegate.deleteProcess(mainEntity);
		buscarMaestro();
		limpiarMaestro();
		log.info("fin eliminarMaestro");	
		
	}

	@Override
	public void guardarMaestro() {
		
		log.info("inicio guardarMaestro");
		if(esNuevo){
			mainEntity=new Process();
			obtenerDatosFormulario(mainEntity);
			mainEntity.setStatus(new ParameterDetail(Constantes.ESTADOPROCESO.DESARROLLO));
			mainEntity.setDiagramHeight(Constantes.Default.DIAGRAM_HEIGHT);
			mainEntity.setDiagramWidth(Constantes.Default.DIAGRAM_WIDTH);
			workflowDelegate.createProcess(mainEntity);
		} else{
			obtenerDatosFormulario(mainEntity);
			//mainEntity.setStatus(new ParameterDetail(Constantes.ESTADOPROCESO.DESARROLLO));
			workflowDelegate.updateProcess(mainEntity);
		}
		limpiarMaestro();
		buscarMaestro();
		log.info("fin guardarMaestro");
	}

	@Override
	public void buscarDetalle() {
		
		
	}

	@Override
	public void buscarDetalle(TextChangeEvent event) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void limpiarDetalle() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void eliminarDetalle() {
		// TODO Auto-generated method stub

	}

	@Override
	public void guardarDetalle() {
		// TODO Auto-generated method stub
		
	}

	@Override
	protected void postConstruct() {
		cargarFormulario();
		buscarMaestro();
		
	}

	private void obtenerDatosFormulario(Process process) {
			
		process.setName(getStringData(txtNombre,"Nombre"));
		process.setDatasource(getObjectData(cmbDatasource, Datasource.class, "Datasource"));
		process.setDescription(getStringData(txaDescripcion,"Description"));
		process.setTimeUnit(getObjectData(cmbUnitTime, ParameterDetail.class, "Unidad de Tiempo"));
		process.setProcessCategory(getObjectData(cmbProcessCat, ParameterDetail.class, "Categoria"));
		process.setTimeAmount(getDoubleData(txtTimeAmount,"Tiempo"));
			
	}
	
	private void verFlujo(){
		Window window=new Window();
		window.setStyleName("titulo-bold");
		
		window.setModal(false);
		window.setResizable(false);
		
		window.setCaption("DETALLE DEL PROCESO");
		
		//FlowDesignerUI flowDesignerUI =new FlowDesignerUI(mainEntity);
		ProcessDetailUI flowDesignerUI =new ProcessDetailUI(mainEntity);
		VerticalLayout layout=new VerticalLayout();
		layout.addComponent(flowDesignerUI);
		layout.setMargin(true);
		window.setContent(layout);
		//window.setHeight("700");
		//window.setWidth("1500");
		window.setSizeFull();
		UI.getCurrent().addWindow(window);
	}

@AutoGenerated
private VerticalLayout buildMainLayout() {
	// common part: create layout
	mainLayout = new VerticalLayout();
	mainLayout.setImmediate(false);
	mainLayout.setWidth("-1px");
	mainLayout.setHeight("-1px");
	mainLayout.setMargin(false);
	
	// top-level component properties
	setWidth("-1px");
	setHeight("-1px");
	
	// verticalLayout_1
	verticalLayout_1 = buildVerticalLayout_1();
	mainLayout.addComponent(verticalLayout_1);
	
	return mainLayout;
}


@AutoGenerated
private VerticalLayout buildVerticalLayout_1() {
	// common part: create layout
	verticalLayout_1 = new VerticalLayout();
	verticalLayout_1.setImmediate(false);
	verticalLayout_1.setWidth("-1px");
	verticalLayout_1.setHeight("-1px");
	verticalLayout_1.setMargin(false);
	verticalLayout_1.setSpacing(true);
	
	// horizontalLayout_1
	horizontalLayout_1 = buildHorizontalLayout_1();
	verticalLayout_1.addComponent(horizontalLayout_1);
	
	return verticalLayout_1;
}


@AutoGenerated
private HorizontalLayout buildHorizontalLayout_1() {
	// common part: create layout
	horizontalLayout_1 = new HorizontalLayout();
	horizontalLayout_1.setImmediate(false);
	horizontalLayout_1.setWidth("-1px");
	horizontalLayout_1.setHeight("-1px");
	horizontalLayout_1.setMargin(false);
	horizontalLayout_1.setSpacing(true);
	
	// lytMaestroProcess
	lytMaestroProcess = buildLytMaestroProcess();
	horizontalLayout_1.addComponent(lytMaestroProcess);
	
	// verticalLayout_5
	verticalLayout_5 = buildVerticalLayout_5();
	horizontalLayout_1.addComponent(verticalLayout_5);
	
	return horizontalLayout_1;
}


@AutoGenerated
private HorizontalLayout buildLytMaestroProcess() {
	// common part: create layout
	lytMaestroProcess = new HorizontalLayout();
	lytMaestroProcess.setImmediate(false);
	lytMaestroProcess.setWidth("-1px");
	lytMaestroProcess.setHeight("-1px");
	lytMaestroProcess.setMargin(false);
	lytMaestroProcess.setSpacing(true);
	
	// lytTablaProcess
	lytTablaProcess = buildLytTablaProcess();
	lytMaestroProcess.addComponent(lytTablaProcess);
	
	return lytMaestroProcess;
}


@AutoGenerated
private HorizontalLayout buildLytTablaProcess() {
	// common part: create layout
	lytTablaProcess = new HorizontalLayout();
	lytTablaProcess.setImmediate(false);
	lytTablaProcess.setWidth("480px");
	lytTablaProcess.setHeight("-1px");
	lytTablaProcess.setMargin(false);
	
	// tblfMaestro
	tblfMaestro = new TableCustom();
	tblfMaestro.setImmediate(false);
	tblfMaestro.setWidth("-1px");
	tblfMaestro.setHeight("-1px");
	lytTablaProcess.addComponent(tblfMaestro);
	
	return lytTablaProcess;
}


@AutoGenerated
private VerticalLayout buildVerticalLayout_5() {
	// common part: create layout
	verticalLayout_5 = new VerticalLayout();
	verticalLayout_5.setImmediate(false);
	verticalLayout_5.setWidth("-1px");
	verticalLayout_5.setHeight("-1px");
	verticalLayout_5.setMargin(false);
	verticalLayout_5.setSpacing(true);
	
	// lbltitulo
	lbltitulo = new Label();
	lbltitulo.setImmediate(false);
	lbltitulo.setWidth("-1px");
	lbltitulo.setHeight("-1px");
	lbltitulo.setValue("PROCESO");
	verticalLayout_5.addComponent(lbltitulo);
	
	// txtNombre
	txtNombre = new TextField();
	txtNombre.setImmediate(false);
	txtNombre.setDescription("Nombre");
	txtNombre.setWidth("200px");
	txtNombre.setHeight("-1px");
	txtNombre.setInputPrompt("Nombre");
	txtNombre.setMaxLength(50);
	verticalLayout_5.addComponent(txtNombre);
	
	// cmbDatasource
	cmbDatasource = new ComboBox();
	cmbDatasource.setImmediate(false);
	cmbDatasource.setWidth("194px");
	cmbDatasource.setHeight("-1px");
	verticalLayout_5.addComponent(cmbDatasource);
	
	// cmbUnitTime
	cmbUnitTime = new ComboBox();
	cmbUnitTime.setImmediate(false);
	cmbUnitTime.setWidth("194px");
	cmbUnitTime.setHeight("-1px");
	verticalLayout_5.addComponent(cmbUnitTime);
	
	// txtTimeAmount
	txtTimeAmount = new TextField();
	txtTimeAmount.setImmediate(false);
	txtTimeAmount.setWidth("200px");
	txtTimeAmount.setHeight("-1px");
	txtTimeAmount.setInputPrompt("Tiempo");
	txtTimeAmount.setMaxLength(20);
	verticalLayout_5.addComponent(txtTimeAmount);
	
	// cmbProcessCat
	cmbProcessCat = new ComboBox();
	cmbProcessCat.setImmediate(false);
	cmbProcessCat.setWidth("194px");
	cmbProcessCat.setHeight("-1px");
	verticalLayout_5.addComponent(cmbProcessCat);
	
	// txaDescripcion
	txaDescripcion = new TextArea();
	txaDescripcion.setImmediate(false);
	txaDescripcion.setWidth("200px");
	txaDescripcion.setHeight("-1px");
	verticalLayout_5.addComponent(txaDescripcion);
	
	// horizontalLayout_5
	horizontalLayout_5 = buildHorizontalLayout_5();
	verticalLayout_5.addComponent(horizontalLayout_5);
	
	// horizontalLayout_2
	horizontalLayout_2 = buildHorizontalLayout_2();
	verticalLayout_5.addComponent(horizontalLayout_2);
	
	return verticalLayout_5;
}


@AutoGenerated
private HorizontalLayout buildHorizontalLayout_5() {
	// common part: create layout
	horizontalLayout_5 = new HorizontalLayout();
	horizontalLayout_5.setImmediate(false);
	horizontalLayout_5.setWidth("-1px");
	horizontalLayout_5.setHeight("-1px");
	horizontalLayout_5.setMargin(false);
	horizontalLayout_5.setSpacing(true);
	
	// btnModificar
	btnModificar = new Button();
	btnModificar.setCaption("Modificar");
	btnModificar.setImmediate(true);
	btnModificar.setWidth("80px");
	btnModificar.setHeight("-1px");
	horizontalLayout_5.addComponent(btnModificar);
	
	// btnEliminar
	btnEliminar = new Button();
	btnEliminar.setCaption("Eliminar");
	btnEliminar.setImmediate(true);
	btnEliminar.setWidth("80px");
	btnEliminar.setHeight("-1px");
	horizontalLayout_5.addComponent(btnEliminar);
	
	// btnNuevo
	btnNuevo = new Button();
	btnNuevo.setCaption("Nuevo");
	btnNuevo.setImmediate(true);
	btnNuevo.setWidth("80px");
	btnNuevo.setHeight("-1px");
	horizontalLayout_5.addComponent(btnNuevo);
	
	return horizontalLayout_5;
}


@AutoGenerated
private HorizontalLayout buildHorizontalLayout_2() {
	// common part: create layout
	horizontalLayout_2 = new HorizontalLayout();
	horizontalLayout_2.setImmediate(false);
	horizontalLayout_2.setWidth("-1px");
	horizontalLayout_2.setHeight("-1px");
	horizontalLayout_2.setMargin(false);
	horizontalLayout_2.setSpacing(true);
	
	// btnDetalle
	btnDetalle = new Button();
	btnDetalle.setCaption("Detalle");
	btnDetalle.setImmediate(true);
	btnDetalle.setWidth("80px");
	btnDetalle.setHeight("-1px");
	horizontalLayout_2.addComponent(btnDetalle);
	
	// btnPublicar
	btnPublicar = new Button();
	btnPublicar.setCaption("Publicar");
	btnPublicar.setImmediate(true);
	btnPublicar.setWidth("80px");
	btnPublicar.setHeight("-1px");
	horizontalLayout_2.addComponent(btnPublicar);
	
	return horizontalLayout_2;
}
	
	
}
